import 'dart:async';
import 'dart:io';
import 'dart:ui';

import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/network/http_request.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/pay/change_pay.dart';
import 'package:fate_blind_box/ui/pay/payout.dart';
import 'package:fate_blind_box/ui/user/Invite4.dart';
import 'package:fate_blind_box/utils/bottom_sheet.dart';
import 'package:fate_blind_box/utils/default/common_config.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tcard/tcard.dart';

import '../../utils/default/over_lay_filter_view.dart';
import '../../utils/page.dart';
import '../account/scan/scan_main_page.dart';
import '../user/profile.dart';

class BlindBox2Ui extends StatefulWidget {
  const BlindBox2Ui({Key? key}) : super(key: key);

  @override
  State<BlindBox2Ui> createState() => _BlindBox2WidgetState();
}

class _BlindBox2WidgetState extends State<BlindBox2Ui> {
  final _tCardController = TCardController();

  int _totalCount = 0;
  final List _blindList = <dynamic>[];
  late Size _screenSize;
  Map<dynamic, dynamic> map = {};

  int chenkid = 0;
  final List isOpenSign = <dynamic>[];
  final List _listData = <dynamic>[];

  //是否是右滑
  bool isRight = false;

  //是否是第一次右滑，目的是只调用一次看过的数据
  bool isSeedRight = false;

  //用户拆过的数据
  List _seedData = <dynamic>[];
  bool isOnlyOneRight = false;

  @override
  void initState() {
    super.initState();
    if (CommonConfig.isShowGuide == false) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        OverLayFilerView.showView(context);
        CommonConfig.isShowGuide = true;
      });
    }

    Future.delayed(const Duration(seconds: 5)).then((value) {
      OverLayFilerView.dismiss();
    });

    _getData();
  }

  _getData() {
    //推荐(左滑惊喜)
    loading(() async {
      final blindRes = await Api.getInstance().blindList();
      final countRes = await Api.getInstance().blindChance();
      _totalCount = countRes['data']?['total'] ?? 0;
      List blindData = blindRes['data'];
      if (blindData.isNotEmpty) {
        if (mounted) {
          setState(() {
            _blindList.clear();
            _blindList == [];
            _blindList.addAll(blindRes['data']);
          });
        }
        isOpenSign.clear();
        isOpenSign == [];
        for (var item in _blindList) {
          isOpenSign.add({"isOpenSign": 0});
        }
        if (_tCardController.state != null) {
          _tCardController.reset();
        }
      } else {
        //空的话，调用已经看过的接口
        _getMeLookListLeft(1);
      }
    });
  }

  ///第一次右滑，还没有看过的数据，加载左滑数据
  _getRightData() {
    loading(() async {
      final blindRes = await Api.getInstance().blindList();
      final countRes = await Api.getInstance().blindChance();
      _totalCount = countRes['data']?['total'] ?? 0;
      List blindData = blindRes['data'];
      if (blindData.isNotEmpty) {
        setState(() {
          _listData.clear();
          _listData == [];
          // _listData.addAll(blindRes['data']);
          _listData.add(blindData[0]);
        });
        isOpenSign.clear();
        isOpenSign == [];
        // for(var item in _listData) {
        isOpenSign.add({"isOpenSign": 0});
        // }
        _tCardController.reset();
      }
    });
  }

  _blindOpen(String id) async {
    if (_totalCount < 1) {
      final res = await BottomSheetDialog.show(context, const PayoutWidget());
      if (res == 1) {
        Navigate.toPage(const Invite4Ui());
      } else if (res == 2) {
        // _getProList();
        final res = await Navigate.toPage(const Pay4ChangeUi());

        if (res != null && res is int && res > 0) {
          setState(() {
            _totalCount += res;
          });
        }
      }
    } else {
      loading(() async {
        print('bbb');
        final res = await Api.getInstance().blindOpen(id);
        if (res["code"] == 0) {
          setState(() {
            _totalCount--;
            isOpenSign[0]['isOpenSign'] = 1;
            // _seedData.add(1);
          });
          await Future.delayed(const Duration(milliseconds: 500));
          _tCardController.reset();
          Navigate.toPage(UserProfileUi(memberId: id));
        } else {
          toast(res['msg']);
        }
      });
    }
  }

  ///左滑所有看完在调用我看过的
  _getMeLookListLeft(int page) async {
    final res = await Api.getInstance().getMeLook(Provider.memberId);
    final data = res['data'];

    if (data != null) {
      isSeedRight = true;
      // isRight = false;
      //有看过的
      List list = data;
      if (list.isNotEmpty) {
        _blindList.clear();
        setState(() {
          _blindList.addAll(list);
        });
      }
      print('cccc ${_blindList.length}');
      isOpenSign.clear();
      isOpenSign == [];
      for (var item in _blindList) {
        isOpenSign.add({"isOpenSign": 1});
      }
      print('zz  $isOpenSign');
      _tCardController.reset();
    } else {
      //还没有看过的，不做处理
    }
  }

  ///我看过的
  _getMeLookList(int page) async {
    final res = await Api.getInstance().getMeLook(Provider.memberId);
    _seedData = res['data'];
    if (_seedData.isNotEmpty) {
      isSeedRight = true;
      // isRight = false;
      //有看过的
      List list = _seedData;
      if (list.isNotEmpty) {
        _listData.clear();
        setState(() {
          _listData.addAll(list);
        });
      }
      print('cccc ${_listData.length}');
      _tCardController.reset();
    } else {
      //还没有看过的，加载未看过的数据（也就是左滑数据）
      _getRightData();
    }
  }

  Widget checktype(dynamic type) {
    double filterValue = CommonConfig.isShowPay() == false ? 0.0 : 6.0;
    // print('------------fff----'+type.toString());
    if (type == 1) {
      return const SizedBox(
        width: 0,
        height: 0,
      );
    } else if (type == 0) {
      return BackdropFilter(
        filter: ImageFilter.blur(sigmaX: filterValue, sigmaY: filterValue),
        child: Container(
            // height: 250,
            // width: 225,
            height: 355,
            width: 296,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10.0),
            )),
      );
    }
    return Container();
  }

  @override
  Widget build(BuildContext context) {
    _screenSize = MediaQuery.of(context).size;
    double cardWidth = 296;
    double cardHeight = 335;
    return Container(
      width: 1.sw,
      height: 1.sh,
      decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage('images/scan/ccym_center_bg.png'),
              fit: BoxFit.cover)),
      child: SingleChildScrollView(
        padding: EdgeInsets.only(
            bottom: ScreenUtil().bottomBarHeight > 0 ? 0 : 44.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              height: ScreenUtil().statusBarHeight,
            ),
            const SizedBox(
              height: 47,
            ),
            CommonConfig.isShowPay() == false
                ? Text(
                    '都肆商圈',
                    style: TextStyle(
                        fontSize: 18,
                        color: ThemeColor.black1414Color,
                        fontWeight: FontWeight.w600),
                  )
                : Image.asset(
                    'images/scan/yjmh_bg_font.png',
                    width: 140,
                  ),
            Offstage(
              offstage: CommonConfig.isShowPay() == false,
              child: Text(
                '拆拆我是谁',
                style:
                    TextStyle(fontSize: 14, color: ThemeColor.hint777777Color),
              ),
            ),
            const SizedBox(
              height: 32,
            ),
            _blindList.isEmpty || (isRight && _listData.isEmpty)
                ? checktype(0)
                : Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Image.asset(
                        'images/box_left.png',
                        width: 28,
                        height: 342,
                      ),
                      Stack(
                        children: [
                          TCard(
                              controller: _tCardController,
                              onEnd: () {
                                print('---3-----------');
                                print('------$isRight   $chenkid $_listData');
                                if (isRight) {
                                  chenkid = 0;
                                  _tCardController.reset();
                                }
                              },
                              onBack: (index, info) {
                                print('---1-----------');
                              },
                              onForward: (index, info) {
                                if (info.direction == SwipDirection.Left) {
                                  if (isRight == true) {
                                    setState(() {
                                      _blindList.clear();
                                      _getData();
                                    });
                                  }

                                  setState(() {
                                    isRight = false;
                                  });

                                  chenkid = index;
                                  // print('bbb $chenkid');
                                  _blindList.removeAt(0);
                                  isOpenSign.removeAt(0);
                                  print(isOpenSign);
                                  print("ccc ${_blindList.length} $index");
                                  if (_blindList.isEmpty) {
                                    setState(() {
                                      _getData();
                                    });
                                  }
                                  _tCardController.state?.setState(() {});
                                } else if (info.direction ==
                                    SwipDirection.Right) {
                                  chenkid = index;
                                  setState(() {
                                    if (isSeedRight == false ||
                                        isRight == false) {
                                      chenkid = 0;
                                      _getMeLookList(1);
                                    }
                                    isRight = true;
                                  });
                                  _tCardController.state?.setState(() {});
                                }
                              },
                              size: Size(cardWidth, cardHeight),
                              cards: !isRight
                                  ? _blindList
                                      .map((e) => Container(
                                            decoration: BoxDecoration(
                                              color: Colors.white,
                                              borderRadius:
                                                  BorderRadius.circular(10.0),
                                              boxShadow: const [
                                                BoxShadow(
                                                  offset: Offset(0, 17),
                                                  blurRadius: 23.0,
                                                  spreadRadius: -13.0,
                                                  color: Colors.black54,
                                                )
                                              ],
                                            ),
                                            child: GestureDetector(
                                              onTap: () {
                                                print(
                                                    'nnnn ${e['id']}  ${isOpenSign[_blindList.indexOf(e)]["isOpenSign"]}');
                                                // if (e['openSign'] == 1) {
                                                if (isOpenSign[_blindList
                                                            .indexOf(e)]
                                                        ["isOpenSign"] ==
                                                    1) {
                                                  Navigate.toPage(UserProfileUi(
                                                      memberId: e['id']));
                                                } else {
                                                  _blindOpen(e['id']);
                                                }
                                              },
                                              child: ClipRRect(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          10.0),
                                                  child: Stack(
                                                    children: [
                                                      Image.network(
                                                        Provider.fixAvatar(
                                                            e['profilePhoto']),
                                                        fit: BoxFit.cover,
                                                        width: cardWidth,
                                                        height: cardHeight,
                                                      ),
                                                      // checktype(_blindList[chenkid]["openSign"]),
                                                      checktype(isOpenSign[
                                                          _blindList.indexOf(
                                                              e)]["isOpenSign"])
                                                    ],
                                                  )),
                                            ),
                                          ))
                                      .toList()
                                  : _listData
                                      .map((e) => Container(
                                            decoration: BoxDecoration(
                                              color: Colors.white,
                                              borderRadius:
                                                  BorderRadius.circular(10.0),
                                              boxShadow: const [
                                                BoxShadow(
                                                  offset: Offset(0, 17),
                                                  blurRadius: 23.0,
                                                  spreadRadius: -13.0,
                                                  color: Colors.black54,
                                                )
                                              ],
                                            ),
                                            child: GestureDetector(
                                              onTap: () {
                                                print('nnnn ${e['id']}');
                                                if (_seedData.isEmpty) {
                                                  isOnlyOneRight = true;
                                                  _blindOpen(e['id']);
                                                } else {
                                                  Navigate.toPage(UserProfileUi(
                                                      memberId: e['id']));
                                                }
                                              },
                                              child: ClipRRect(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          10.0),
                                                  child: Stack(
                                                    children: [
                                                      Image.network(
                                                        Provider.fixAvatar(
                                                            e['profilePhoto']),
                                                        fit: BoxFit.cover,
                                                        width: cardWidth,
                                                        height: cardHeight,
                                                      ),
                                                      isOpenSign[0]['isOpenSign'] ==
                                                                  1 ||
                                                              _seedData
                                                                  .isNotEmpty
                                                          ? checktype(1)
                                                          : checktype(0)
                                                    ],
                                                  )),
                                            ),
                                          ))
                                      .toList()),
                          !isRight
                              ? Positioned(
                                  bottom: 40,
                                  right: 35,
                                  child: Visibility(
                                    visible: CommonConfig.isShowPay(),
                                    child: GestureDetector(
                                      onTap: () {
                                        if (_totalCount < 1) {
                                          jumpPayView();
                                        }
                                      },
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 8, vertical: 4),
                                        decoration: BoxDecoration(
                                            color: const Color(0xFFEBFCFF),
                                            border: Border.all(
                                                color: const Color.fromRGBO(
                                                  95,
                                                  126,
                                                  240,
                                                  0.29,
                                                ),
                                                width: 1),
                                            borderRadius:
                                                BorderRadius.circular(23)),
                                        child: Text(
                                          '剩余$_totalCount次机会',
                                          style: const TextStyle(
                                              color: Color(
                                                0xFF5C7DF5,
                                              ),
                                              fontSize: 12),
                                        ),
                                      ),
                                    ),
                                  ),
                                )
                              : const SizedBox()
                        ],
                      ),
                      Image.asset(
                        'images/box_right.png',
                        width: 28,
                        height: 342,
                      ),
                    ],
                  ),
            const SizedBox(
              height: 18,
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 30),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  getCornerBtnView(
                    tapAction: () {
                      Get.to(ScanMainPage(
                        refreshBlock: (codeStr) {
                          getLatestMatchData(codeStr);
                        },
                      ));
                    },
                    width: 72,
                    colors: const [
                      Color(0xFF99BBFF),
                      Color(0xFF58ABF7),
                    ],
                    shadowColor: const Color.fromRGBO(88, 171, 247, 0.15),
                    childWidget: Image.asset(
                      'images/scan/main_scan_white.png',
                      width: 24,
                    ),
                  ),
                  Visibility(
                    visible:
                        Platform.isAndroid ? true : CommonConfig.isShowPay(),
                    child: getCornerBtnView(
                      tapAction: () {
                        jumpPayView();
                      },
                      width: 124.w,
                      colors: const [
                        Color(0xFFD175FE),
                        Color(0xFF747CF8),
                      ],
                      shadowColor: const Color.fromRGBO(127, 105, 217, 0.15),
                      childWidget: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 14),
                        child: Row(
                          children: [
                            Image.asset(
                              'images/scan/main_scan_add.png',
                              width: 18,
                            ),
                            const SizedBox(
                              width: 6,
                            ),
                            const Text(
                              '增加机会',
                              style:
                                  TextStyle(fontSize: 18, color: Colors.white),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  getCornerBtnView(
                    tapAction: () {
                      if (!isRight) {
                        if (isOpenSign[0]['isOpenSign'] != 1) {
                          if (_blindList[0]['id'].toString().isEmpty) return;
                          _blindOpen(_blindList[0]['id']);
                        } else {
                          Navigate.toPage(
                              UserProfileUi(memberId: _blindList[0]['id']));
                        }
                      } else {
                        if (_seedData.isEmpty) {
                          isOnlyOneRight = true;
                          _blindOpen(_listData[0]['id']);
                        } else {
                          if (isOnlyOneRight || _seedData.length == 1) {
                            Navigate.toPage(
                                UserProfileUi(memberId: _listData[0]['id']));
                          } else {
                            Navigate.toPage(UserProfileUi(
                                memberId: _listData[chenkid]['id']));
                          }
                        }
                      }
                    },
                    width: 72,
                    colors: const [
                      Color(0xFFFF9999),
                      Color(0xFFF75858),
                    ],
                    shadowColor: const Color.fromRGBO(247, 88, 88, 0.15),
                    childWidget: Text(
                      CommonConfig.isShowPay() == false ? '点点看' : '拆拆看',
                      style: const TextStyle(color: Colors.white, fontSize: 18),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget getCornerBtnView(
      {double width = 0,
      double height = 0,
      Widget? childWidget,
      List<Color>? colors,
      Color? shadowColor,
      Function? tapAction}) {
    return GestureDetector(
      onTap: () {
        if (tapAction != null) {
          tapAction();
        }
      },
      child: Container(
        width: width,
        height: 46,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(23),
            boxShadow: [
              BoxShadow(
                  color:
                      shadowColor ?? const Color.fromRGBO(88, 171, 247, 0.15),
                  blurStyle: BlurStyle.solid,
                  blurRadius: 4,
                  offset: Offset(0, 4))
            ],
            gradient: LinearGradient(
                colors: colors ?? [],
                begin: Alignment.centerLeft,
                end: Alignment.centerRight)),
        child: childWidget ?? Container(),
      ),
    );
  }

  jumpPayView() async {
    // if (Platform.isIOS && CommonConfig.isHiddenOpen == 1) {
    //   _blindList.clear();
    //   _getMeLookListLeft(1);
    //   return;
    // }
    jumpShowPayView();
  }

  void jumpShowPayView() async {
    final res = await BottomSheetDialog.show(context, const PayoutWidget());
    if (res == 1) {
      Navigate.toPage(const Invite4Ui());
    } else if (res == 2) {
      // _getProList();
      final res = await Navigate.toPage(const Pay4ChangeUi());
      print(res);
      if (res != null && res is int && res > 0) {
        setState(() {
          _totalCount += res;
        });
      }
    }
  }

  getLatestMatchData(String codeStr) async {
    var res = await HttpRequest.request('match-maker/business/scanWhoIShere',
        params: {"shareCode": codeStr});
    if (res != null && res['code'] == 0) {
      if (res['data'] != null) {
        List dataList = res['data'];
        if (isRight == true) {
          _blindList.removeAt(0);
          isOpenSign.removeAt(0);
          isRight = false;
        }
        if (dataList.isNotEmpty) {
          setState(() {
            _blindList.clear();
            _blindList == [];
            _blindList.addAll(dataList);
            isOpenSign.clear();
            isOpenSign == [];
            for (var item in _blindList) {
              isOpenSign.add({"isOpenSign": 0});
            }
            _tCardController.reset();
          });
        } else {
          //空的话，调用已经看过的接口
          _getMeLookListLeft(1);
        }
      }
    }
  }
}
